package com.car.rental.gateway.handler;

import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import java.util.Optional;

@Slf4j
@Order(-1)
@Component
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    @NonNull
    public Mono<Void> handle(@NonNull ServerWebExchange exchange, @NonNull Throwable ex) {
        String path = exchange.getRequest().getURI().getPath();
        String method = Optional.ofNullable(exchange.getRequest().getMethod())
            .map(Enum::name)
            .orElse("UNKNOWN");
        
        log.error("网关异常: 路径={}, 方法={}, 错误={}", path, method, ex.getMessage());
        log.error("详细错误: ", ex);
        
        exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        return exchange.getResponse().setComplete();
    }
} 